﻿#region Imports

using System;
using System.Collections.Generic;
using System.IO;
using d3PrtDgn.Common.Common;
using d3PrtDgn.Data.IDAO;

#endregion

namespace d3PrtDgn.Web.Admin
{
	/// <summary>
	/// Statistics page
	/// </summary>
	public partial class Statistics : Page
	{
		#region Private fields

		private IUserDao userDao;

		#endregion

		#region Public properties

		/// <summary>
		/// Sets user DAO
		/// </summary>
		public IUserDao UserDao
		{
			set { userDao = value; }
		}

		#endregion

		#region Event handlers

		/// <summary>
		/// Initializes page
		/// </summary>
		/// <param name="e"></param>
		protected override void OnInit(EventArgs e)
		{
			if (SignedInUser.Id == 0 || SignedInUser.Username != "admin")
				SetResult("Login");

			base.OnInit(e);
		}

		/// <summary>
		/// Handles on load actions
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		protected void Page_Load(object sender, EventArgs e)
		{
			InitUsage();
		}

		#endregion

		#region Private methods

		/// <summary>
		/// Initializes usage grid
		/// </summary>
		private void InitUsage()
		{
            IList<Data.Domain.Entity.User> users = userDao.FindAll();
			IList<StatBinding> res = new List<StatBinding>();

            foreach (Data.Domain.Entity.User user in users)
			{
				string photosPath = Server.MapPath(Constants.basePath + "/user" + user.Id);
				string thumbsPath = Server.MapPath(Constants.thumbPath + "/user" + user.Id);
				string detailsPath = Server.MapPath(Constants.detailPath + "/user" + user.Id);

				long size = 0;
				size += DirectorySize(photosPath);
				size += DirectorySize(thumbsPath);
				size += DirectorySize(detailsPath);

				StatBinding pair = new StatBinding();
				pair.Username = user.Username;
				pair.Usage = size;

				res.Add(pair);
			}

			gvDiscUsage.DataSource = res;
			gvDiscUsage.DataBind();
		}

		/// <summary>
		/// Counts size of directory
		/// </summary>
		/// <param name="path"></param>
		/// <returns></returns>
		private static long DirectorySize(string path)
		{
			long size = 0;

			if (Directory.Exists(path))
			{
				string[] files = Directory.GetFiles(path);
				foreach (string file in files)
				{
					FileInfo f = new FileInfo(file);
					size += f.Length;
				}
			}

			return size;
		}

		#endregion
	}

	#region Binding helper class for statistics grid

	/// <summary>
	/// Sealed class just for binding to grid
	/// </summary>
	sealed class StatBinding
	{
		private string username;
		private long usage;

		public string Username
		{
			get { return username; }
			set { username = value; }
		}

		public long Usage
		{
			get { return usage; }
			set { usage = value; }
		}
	}

	#endregion
}
